<template>
  <el-row style="justify-content: center;align-items:center;height: 5vh;padding-left: 2%;padding-right: 3%;padding-bottom: 4%">
    <el-col :span="24">
      <el-radio-group v-model="radio" size="large" >
        <el-radio-button label="本店分析" />
        <el-radio-button label="商品分析" />
      </el-radio-group>
    </el-col>
  </el-row>
  <div v-if="radio==='本店分析'">
    <el-row style="background-color: white;padding: 0 0 20px 0;">
      <el-col :span="8" style="text-align: center;padding: 15px 15px 15px 15px;" >
        <div>
          <el-statistic :value="storeAnalysis.salesVolume" precision="2" :value-style="{fontSize: '30px'}">
            <template #title>
              <div style="display: inline-flex; align-items: center">
                近7天销售额(元)
              </div>
            </template>
          </el-statistic>
          <div >
            <div >
              <span>较前4周均值</span>
              <span :class="storeAnalysis.compareWithSalesVolume<0?'red':'green'">
              {{ Math.abs(storeAnalysis.compareWithSalesVolume)}}
              <el-icon>
                <CaretBottom v-if="storeAnalysis.compareWithSalesVolume<0"/>
                <CaretTop v-else/>
              </el-icon>
            </span>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="8" style="text-align: center;padding: 15px 15px 15px 15px;">
        <div>
          <el-statistic :value="storeAnalysis.transactionsNum" :value-style="{fontSize: '30px'}">
            <template #title>
              <div style="display: inline-flex; align-items: center">
                近7天销售笔数
              </div>
            </template>
          </el-statistic>
          <div>
            <div>
              <span>较前4周均值</span>
              <span :class="storeAnalysis.compareWithTransactionsNum <0?'red':'green'">
              {{ Math.abs(storeAnalysis.compareWithTransactionsNum) }}
              <el-icon>
                <CaretBottom v-if="storeAnalysis.compareWithTransactionsNum<0"/>
                <CaretTop v-else/>
              </el-icon>
            </span>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="8" style="text-align: center;padding: 15px 15px 15px 15px;">
        <div>
          <el-statistic :value="storeAnalysis.turnoverRate * 100+'%'" precision="2" :value-style="{fontSize: '30px'}">
            <template #title>
              <div style="display: inline-flex; align-items: center">
                商品动销率
              </div>
            </template>
          </el-statistic>
        </div>
      </el-col>
    </el-row>
    <el-row style="background-color: white;padding: 0 0 20px 0;height: 500px">
      <div style="min-width: 100%; height: 100%;">
        <div id="myChart" style="width: 100%; height: 100%;"></div>
      </div>
    </el-row>
  </div>
  <div v-else>
    <el-row style="justify-content: center;align-items:center;height: 5vh;padding-left: 2%;padding-right: 3%">
      <el-col :span="24" style="text-align: right;padding-right: 2%">
        <el-select v-model="curType" placeholder="选择类别" size="large" @change="handleSelect" style="width: 20%;">
          <el-option
              v-for="item in typeList"
              :key="item"
              :label="item"
              :value="item"
          />
        </el-select>
      </el-col>
    </el-row>
    <div style="margin-top: 2vh">
      <el-table :data="tableData(curGoodsAnalysis)"
                height="65vh"
                style="width: 100%;"
                :header-cell-style="{ background: '#f6f6f6',  }"

      >
        <el-table-column label="商品名称" width="400">
          <template #default="scope">
            <el-row align='middle'>
                  <el-col span="5">
                    <el-image :src="scope.row.image" style="height: 70px;">
                      <template #error>
                        <div class="image-slot">
                          <el-icon><Picture /></el-icon>
                        </div>
                      </template>
                    </el-image>
                  </el-col>
                  <el-col span="19" style="padding-left: 5%;">
                    <el-row style="max-width: 250px">
                      <el-text>
                        {{ store.getLocalStorage(scope.row.code)!=null?store.getLocalStorage(scope.row.code).goodsName:"已删除商品"}}
                      </el-text>
                    </el-row>
                  </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column prop="salesNum" label="近七天销量" />
        <el-table-column prop="beforeAvgSalesVolume" label="前4周销售额均值"/>
        <el-table-column prop="salesVolume" label="近七天销售额"/>
        <el-table-column label="销售额变化">
          <template #default="scope">
            <span>
              {{ Math.abs(scope.row.compareWithSalesVolume) }}
              <el-icon :class="scope.row.compareWithSalesVolume <0?'red':'green'">
                <CaretBottom v-if="scope.row.compareWithSalesVolume<0"/>
                <CaretTop v-else/>
              </el-icon>
            </span>
          </template>
        </el-table-column>
      </el-table>
      <div style="justify-content: center;align-items:center;height: 60px; background-color: rgba(255,255,255,0.72);boxShadow:1px 0px 1px #a6a6a6;z-index: 999;display: flex;padding: 5px 25px 5px 25px;">
        <div style="flex: 4;" >
          <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :background="true"
              layout="->,prev, pager, next, jumper"
              :total="curGoodsAnalysis.length"
              @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {
  CaretBottom,
  CaretTop
} from '@element-plus/icons-vue'
import {nextTick, onMounted, ref, shallowRef, watch} from "vue";
import request from "@/utils/request";
import {store} from "@/store";
import {dateTimeUtils} from "@/utils/dateTimeUtils";
import * as echarts from "echarts";

const radio=ref("本店分析")
const storeAnalysis=ref({})
const goodsAnalysis=ref([])
let businessDate=ref({
  storeId:store.getLocalCurrentStoreMain().storeId,
  startDate:"",
  endDate:""
})
const myChart=shallowRef()
const typeList=ref([])
let curType=ref("全部商品")
let curGoodsAnalysis=ref([])
const currentPage = ref(1)
const pageSize = ref(15)
onMounted(()=>{
  businessDate.value.startDate=dateTimeUtils.getBusinessDateBo(new Date(),-35).formatDateByDay
  businessDate.value.endDate=dateTimeUtils.getBusinessDateBo(new Date()).formatDateByDay
  request.post("/business/get/businessAnalysisReport",businessDate.value).then(res=>{
    console.log(res.data)
    storeAnalysis.value=res.data
    myChart.value = echarts.init(document.getElementById("myChart"));
    updateChartData()
  })
  request.post("/business/get/businessAnalysisReportByGoods",businessDate.value).then(res=>{
    goodsAnalysis.value=res.data.sort(function (a, b) {
      return Math.abs(b.compareWithSalesVolume)-(Math.abs(a.compareWithSalesVolume))
    })
    curGoodsAnalysis.value=goodsAnalysis.value
    for (let i in res.data){
      if (typeList.value.indexOf(res.data[i].goodsType)===-1)
        typeList.value.push(res.data[i].goodsType)
    }
    typeList.value.unshift("全部商品")
  })
})
const updateChartData=()=>{

  let row=Object.keys(storeAnalysis.value.trendChartMap)
  let col=[]
  row.sort(function (a, b) {
    return a.localeCompare(b)
  })

  for (let i in row){
    col.push(storeAnalysis.value.trendChartMap[row[i]].salesVolume)
  }
  myChart.value.setOption({
    title: {
      text: '近35天销售额趋势图'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    xAxis: {
      type: 'category',
      data: row
    },
    yAxis: {},
    series: [
      {
        type: 'line',
        data: col
      },
    ],
    visualMap: {
      show: false,
      dimension: 0,
      pieces: [
        {
          gt: 27,
          lte: 34,
          color: 'blue'
        }
      ],  //pieces的值由动态数据决定
      outOfRange: {
        color: 'grey'
      }
    }
  });
}
const filList = (key,list) => {
  if (key==="全部商品")
    key=""
  // 返回过滤后的数组
  return list.filter((p)=>{
    return p.goodsType.indexOf(key) !==-1
  })
}
const handleSelect = (key) => {
  curType.value=key
  curGoodsAnalysis.value=filList(key,goodsAnalysis.value)
}
const tableData = (list) => {
  return list.filter(
      (item, index) =>
          index < currentPage.value * pageSize.value &&
          index >= pageSize.value * (currentPage.value - 1)
  );
};
const handleCurrentChange = (e) => {
  currentPage.value = e;
};
watch(radio,(n,o)=>{
  if (n==="本店分析"){
    nextTick(() => {
      myChart.value = echarts.init(document.getElementById("myChart"));
      updateChartData()
    })

  }
})
</script>

<style scoped>
.green {
  color: var(--el-color-success);
}
.red {
  color: var(--el-color-error);
}
</style>